package com.hzcx.app.simplechat.util;

import android.content.Context;
import android.content.Intent;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.style.ClickableSpan;
import android.util.Patterns;
import android.view.View;

import com.hzcx.app.simplechat.MyApplication;
import com.hzcx.app.simplechat.R;
import com.hzcx.app.simplechat.ui.publicui.WebViewActivity;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TextHttpUtil {

    public static TextHttpUtil httpUtil = null;
    private static Context context;
    public boolean isLongClick=false;

    public static TextHttpUtil getInstance(Context cxt) {
        if (httpUtil == null) {
            httpUtil = new TextHttpUtil();
            context = cxt;
        }
        return httpUtil;
    }

    private String pattern =
            "((http|ftp|https)://)(([a-zA-Z0-9\\._-]+\\.[a-zA-Z]{2,6})|([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}))(:[0-9]{1,4})*(/[a-zA-Z0-9\\&%_\\./-~-]*)?|(([a-zA-Z0-9\\._-]+\\.[a-zA-Z]{2,6})|([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}))(:[0-9]{1,4})*(/[a-zA-Z0-9\\&%_\\./-~-]*)?";

    Pattern r = Pattern.compile(pattern);
    Matcher m;

    public void setLongClick(boolean isLongClick){
        this.isLongClick=isLongClick;
    }

    public SpannableStringBuilderForAllvers identifyUrl(CharSequence text) {
        CharSequence contextText;
        CharSequence clickText;
        text = text == null ? "" : text;
        //以下用于拼接本来存在的spanText
        SpannableStringBuilderForAllvers span = new SpannableStringBuilderForAllvers(text);
        ClickableSpan[] clickableSpans = span.getSpans(0, text.length(), ClickableSpan.class);
        if (clickableSpans.length > 0) {
            int start = 0;
            int end = 0;
            for (int i = 0; i < clickableSpans.length; i++) {
                start = span.getSpanStart(clickableSpans[0]);
                end = span.getSpanEnd(clickableSpans[i]);
            }
            //可点击文本后面的内容页
            contextText = text.subSequence(end, text.length());
            //可点击文本
            clickText = text.subSequence(start, end);
        } else {
            contextText = text;
            clickText = null;
        }
        m = r.matcher(contextText);
        //匹配成功
        while (m.find()) {
            //得到网址数m.group()
            if (m.start() < m.end()) {
                span.setSpan(new LinkClickSpan(m.group(), m.group(), mUrlSpanClickListener),
                        m.start(), m.end(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            }
        }
        return span;
    }

    private static final String HTTPS = "https://";
    private static final String HTTP = "http://";
    private static final String FTP = "ftp://";

    public static boolean hasNetUrlHead(String url) {
        return (!TextUtils.isEmpty(url)) && (url.startsWith(HTTP) || url.startsWith(HTTPS) || url.startsWith(FTP));
    }

    private UrlSpanClickListener mUrlSpanClickListener = new UrlSpanClickListener() {
        @Override
        public void onClick(View view, String url, String content) {
            if(isLongClick){
                isLongClick=false;
                return;
            }
            if (TextUtils.isEmpty(url)) {
                return;
            }
            Matcher url_matcher = Patterns.WEB_URL.matcher(url);
            if (url_matcher.matches()) {
                String tempUrl;
                if (hasNetUrlHead(url)) {
                    tempUrl = url;
                } else {
                    tempUrl = HTTPS + url;
                }
                //通过webview打开相应的url

                //Bundle bundle = new Bundle();
                //bundle.putString(WebCordovaBaseFragment.EXTRA_URL, tempUrl);
                //bundle.putBoolean(WebCordovaBaseFragment.ENABLE_WEB_TITLE, true);
                //WebViewActivity.presentWeb(Utilities.getApplicationContext(), WebViewActivity.class, WebCommonFragment.class, content, bundle);

                context.startActivity(new Intent(context, WebViewActivity.class)
                        .putExtra(WebViewActivity.INTENT_WEB_URL, tempUrl));
            }
        }
    };

    public interface UrlSpanClickListener {
        void onClick(View view, String url, String content);
    }


    public static class LinkClickSpan extends ClickableSpan {
        private int mColor = MyApplication.getContext().getResources().getColor(R.color.color_0057E6);
        private String mUrl;
        private String mContent;
        UrlSpanClickListener mClickListener;

        public LinkClickSpan(String url, String content, UrlSpanClickListener onClickListener) {
            super();
            mUrl = url;
            mContent = content;
            mClickListener = onClickListener;
        }

        @Override
        public void updateDrawState(TextPaint ds) {
            ds.setColor(mColor);
            ds.linkColor = mColor;
            ds.setUnderlineText(true);//设置是否下划线
            ds.clearShadowLayer();
        }

        @Override
        public void onClick(View widget) {
            if (mClickListener != null) {
                mClickListener.onClick(widget, mUrl, mContent);
            }
        }
    }

    public class SpannableStringBuilderForAllvers extends SpannableStringBuilder {

        public SpannableStringBuilderForAllvers() {
            super("");
        }

        public SpannableStringBuilderForAllvers(CharSequence text) {
            super(text, 0, text.length());
        }

        public SpannableStringBuilderForAllvers(CharSequence text, int start, int end) {
            super(text, start, end);
        }

        @Override
        public SpannableStringBuilder append(CharSequence text) {
            if (text == null) {
                return this;
            }
            int length = length();
            return (SpannableStringBuilderForAllvers) replace(length, length, text, 0, text.length());
        }

        /**
         * 该方法在原API里面只支持API21或者以上，这里适应低版本
         */
        public SpannableStringBuilderForAllvers append(CharSequence text, Object what, int flags) {
            if (text == null) {
                return this;
            }
            int start = length();
            append(text);
            setSpan(what, start, length(), flags);
            return this;
        }
    }


}
